package com.heima.comment.filter;

import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @作者 itcast
 * @创建日期 2021/1/26 15:37
 **/
@Order(0)
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
@Slf4j
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 判断当前请求的header是是否包含userId信息
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 2. 如果包含 将userId信息 封装wmUser
        String userId = request.getHeader("userId");
        if(StringUtils.isNotBlank(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            // 3. 存入到ThreadLocal中
            WmThreadLocalUtils.setUser(wmUser);
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
